function buildReader(/*int*/ documentType) {
	//Typical JsonReader.  Notice additional meta-data params for defining the core attributes of your json-response
	var reader = new Ext.data.JsonReader({
	    totalProperty: 'documents',
	    successProperty: 'success',
	    messageProperty: 'message',  // <-- New "messageProperty" meta-data
	    idProperty: 'id',
	    root: 'data',
	    fields: buildRecordModelByDocumentType(documentType)
	});
	return reader;
}

function buildStore(/*Ext.data.JsonReader*/reader) {
	//Typical Store collecting the Proxy, Reader and Writer together.
	var store = new Ext.data.GroupingStore({
		proxy: new Ext.data.HttpProxy({
		        url: BASE_URL + 'reports/getDocuments',
		        method: 'POST'
		    }),
	    reader: reader
	});	
	return store;
}

function buildGrid(/*int*/ documentType) {
	var reader = buildReader(documentType);
	var store = buildStore(reader);
	
	var grid = new Ext.grid.GridPanel({
	    width:700,
	    height:500,
	    store: store,
	    trackMouseOver:false,
	    disableSelection:true,
	    loadMask: true,
	    border: false,
	
	    // grid columns
	    colModel: new Ext.ux.grid.LockingColumnModel(buildColumnModelByDocumentType(documentType)),
	
	    view: new Ext.ux.grid.LockingGridView({
	        columnsText: 'Columnas',
	        sortAscText: 'Ordena Ascedentemente',
	        sortDescText: 'Ordenar Descendentemente',
	        lockText : 'Fijar columna',
	        unlockText : 'Liberal columna',
	        //forceFit:true,
	        enableRowBody:true,
	        showPreview:false,
	        getRowClass : function(record, rowIndex, p, store){
	            if(this.showPreview){
	            	// TODO: Make a formatted body with the record rendered
	            	record.data.documentType = parseInt(record.data.documentType);
	                p.body = previewRowRenderer(record.data)
	                return 'x-grid3-row-expanded';
	            }
	            return 'x-grid3-row-collapsed';
	        }
	    }),

	    // add the plugin filters to the grid
	    plugins: [getFilters(documentType)],
	    
	    // paging bar on the bottom
	    bbar: new Ext.PagingToolbar({
	        pageSize: 20,
	        store: store,
	        displayInfo: true,
	        displayMsg: 'Mostrando {0} - {1} de {2} ',
	        beforePageText:'P&aacute;gina',
	        emptyMsg: "No hay documento para mostrar",
	        items:[
	            '-', {
	            pressed: false,
	            disabled: true, // disabled at the moment
	            enableToggle:true,
	            text: 'Vista previa',
	            iconCls: 'silk-application-view-list',
	            toggleHandler: function(btn, pressed){
	                var view = grid.getView();
	                view.showPreview = pressed;
	                view.refresh();
	            }
	        }]
	    })
	});
	
	return grid;
}

// configuring the grid filter
function getFilters(/*int*/ documentType) {
	
	var filters = new Array();
	
	filters = filters.concat([
	    {type: 'numeric', dataIndex: 'id'}, 
	    {type: 'string', dataIndex: 'title'}, 
	    {type: 'string', dataIndex: 'authors'}, 
	    
	//    {
	//        type: 'list',
	//        dataIndex: 'documentType',
	//        options: [
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS, 						myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_THESIS],
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS, 		myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MASTER_THESIS],
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS, 				myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_PHD_THESIS],
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE, 	myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE],
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK, 							myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_BOOK],
	//        	[myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA, 			myApp.DOCUMENT_TYPES_STRINGVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA]
	//        ],
	//        phpMode: true
	//    }, 
	    {type: 'string', dataIndex: 'year'}, 
	    {type: 'string', dataIndex: 'pages'}, 
	    {type: 'string', dataIndex: 'publishedin'}, 
	    {type: 'string', dataIndex: 'abstract'}, 
	    {type: 'string', dataIndex: 'keywords'},
	    {type: 'date', dataIndex: 'created_at', afterText:'Despu&eacute;s del', beforeText:'Antes del', onText:'En el'}
	    ]);
	
	switch( documentType ) {
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS:
			filters = filters.concat([
			    {type: 'string', dataIndex: 'tutors'},
			    {type: 'string', dataIndex: 'department'},
			    {type: 'string', dataIndex: 'faculty'},
			    {type: 'string', dataIndex: 'knowledgearea'}
			]);
			break;
		
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS:
			filters = filters.concat([
  			    {type: 'string', dataIndex: 'tutors'},
  			    {type: 'string', dataIndex: 'department'},
  			    {type: 'string', dataIndex: 'faculty'},
  			    {type: 'string', dataIndex: 'knowledgearea'}
  			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
			filters = filters.concat([
			    {type: 'string', dataIndex: 'tutors'},
			    {type: 'string', dataIndex: 'department'},
			    {type: 'string', dataIndex: 'faculty'},
			    {type: 'string', dataIndex: 'knowledgearea'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
			filters = filters.concat([
  			    {type: 'string', dataIndex: 'city'}
  			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
			filters = filters.concat([
			    {type: 'string', dataIndex: 'city'},
			    {type: 'string', dataIndex: 'edition'},
			    {type: 'string', dataIndex: 'editors'},
			    {type: 'string', dataIndex: 'publisher'},
			    {type: 'string', dataIndex: 'knowledgearea'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
			filters = filters.concat([
  			    {type: 'string', dataIndex: 'edition'},
  			    {type: 'string', dataIndex: 'publisher'},
  			    {type: 'string', dataIndex: 'series_number'}
  			]);
			break;
	}
	
	var gridFilters = new Ext.ux.grid.GridFilters({
	    // encode and local configuration options defined previously for easier reuse
	    encode: false, // json encode the filter query
	    local: myApp.filterType,   // defaults to false (remote filtering)
	    menuFilterText: 'Filtrar',
	    filters: filters
	});  
	return gridFilters;
}

/**
 * This is the start point for the windowsReport by DocumentType
 * @return
 */
function getDocuments() {
	var storeDocumentTypes = new Ext.data.JsonStore({
		proxy: new Ext.data.HttpProxy({
			url: BASE_URL + 'documents/getDocumentTypes',
			method: 'POST'
		}),
		fields: ['id','documentType'],
		root: 'rows'
  	});
	
	var cbDocumentTypes = new Ext.form.ComboBox({
		//name: 'documentType',
      	editable: false,
      	mode: 'local', 
      	triggerAction: 'all',
      	valueField: 'id',
      	displayField: 'documentType',
      	hiddenName: 'documentType',
      	width: 200, 
      	labelSeparator: '',
      	forceSelection: true,
      	//transform: 'documentType',
        lazyRender: true,
        loadingText: 'Cargando...',
        store: storeDocumentTypes,
       
      	listeners: {
			select: function(combo,r,i){ 
				if (grid !== undefined) {
					Ext.destroy(grid);
				}
				var dt = parseInt(r.id);
				grid = buildGrid(dt);
      			win.add(grid);
      			win.doLayout();
      			grid.store.load({params:{documentType:dt,limit:20}});
      		}
	    }
	});
	
	cbDocumentTypes.store.load();
	cbDocumentTypes.store.on('load', function(ds,records,o){
		// setValue function will find a match for id = 1 and will display the displayField
		cbDocumentTypes.setValue(1);
	});
	
//	var cbYears= new Ext.form.ComboBox({
//	 	typeAhead: true,
//	    triggerAction: 'all',
//	    editable: false,
//	    lazyRender:true,
//	    mode: 'local',
//	    forceSelection: true,
//	    autoSelect: true,
//	    selectOnFocus:true,
//	    store: new Ext.data.ArrayStore({
//	    	idIndex: 0,
//	        fields: [
//	            'id',
//	            'year'
//	        ],
//	        data: myApp.years(1900)
//	    }),
//	    valueField: 'id',
//	    displayField: 'year',
//	    listeners: {
//			select: function(combo,r,i){ 
//				if (grid !== undefined) {
//					Ext.destroy(grid);
//				}
//				grid = buildGrid(r.id);
//				win.add(grid);
//				win.doLayout();
//				grid.store.load({params:{year:r.id,limit:20}});
//			}
//		}
//	});
	
    //cbYears.setValue(1900);
	var win = new Ext.Window({
		  title: 'Lista de documentos por Tipo de Documento',
		  layout:'fit',
		  width:800,
		  height:600,
		  closeAction:'hide',
		  plain: true,
		  maximizable: true,
		  modal: true,
	
		  buttons: [{
		      text:'Imprimir',
		      handler: function() {
		      	Ext.ux.Printer.print(grid);
		  		}
		  },{
		      text: 'Cerrar',
		      handler: function(){
		          win.hide();
		      }
		  }],
	
		  tbar: ['Tipo de Documento:', cbDocumentTypes/*, '  ', 'A&ntilde;o:', cbYears*/]
	});
	
	var grid = buildGrid(1);
	win.add(grid);
	win.show();
	grid.store.load({params:{documentType:1,limit:20}});
}

function buildColumnModelByDocumentType(/*int*/ documentType) {
	var columns = new Array();
	
	columns = columns.concat([
		{header: "Id", dataIndex: 'id', sortable: true, filterable: true, hidden: true},
		{header: "T&iacute;tulo", width: 180, dataIndex: 'title', sortable: true, filterable: true/*, renderer: renderTitle*/},
		{header: "Autor", width: 120, dataIndex: 'authors', sortable: true, filterable: true},
		{header: "A&ntilde;o", width: 50, dataIndex: 'year', sortable: true, filterable: true},
		{header: "P&aacute;ginas", width: 50, dataIndex: 'pages', sortable: true},
		{header: "Publicado en", width: 100, dataIndex: 'publishedin', sortable: true, filterable: true},
		{header: "Adicionado", width: 100, dataIndex: 'created_at', sortable: true, renderer: formatDateRenderer},
		{header: "Tipo de Documento", width: 100, dataIndex: 'documentType', sortable: true, renderer: documentTypeRenderer, filterable: true, hidden: true}
	]);
	
	switch( documentType ) {
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS:
			columns = columns.concat([
			  	{header: 'Tutores', dataIndex: 'tutors'},
			    {header: 'Departamento', dataIndex: 'department'},
			    {header: 'Facultad', dataIndex: 'faculty'},
			    {header: '&Aacute;rea del conocimiento', dataIndex: 'knowledgearea'}
			]);
			break;
		
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS:
			columns = columns.concat([
			  	{header: 'Tutores', dataIndex: 'tutors'},
			    {header: 'Departamento', dataIndex: 'department'},
			    {header: 'Facultad', dataIndex: 'faculty'},
			    {header: '&Aacute;rea del conocimiento', dataIndex: 'knowledgearea'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
			columns = columns.concat([
			  	{header: 'Tutores', dataIndex: 'tutors'},
			    {header: 'Departamento', dataIndex: 'department'},
			    {header: 'Facultad', dataIndex: 'faculty'},
			    {header: '&Aacute;rea del conocimiento', dataIndex: 'knowledgearea'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
			columns = columns.concat([
			    {header: 'Ciudad', dataIndex: 'city'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
			columns = columns.concat([
				{header: 'Ciudad', dataIndex: 'city'},
			    {header: 'Edici&oacute;n', dataIndex: 'edition'},
			    {header: 'Editores', dataIndex: 'editors'},
			    {header: 'Publicador', dataIndex: 'publisher'},
			    {header: '&Aacute;rea del conocimiento', dataIndex: 'knowledgearea'}
			]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
			columns = columns.concat([
  			    {header: 'Edici&oacute;n', dataIndex: 'edition'},
  			    {header: 'Publicador', dataIndex: 'publisher'},
  			    {header: 'N&uacute;mero de series', dataIndex: 'series_number'}
  			]);
			break;
	}
	
	return columns;	
}

function buildRecordModelByDocumentType(/*int*/ documentType) {
	var fields = new Array();
	
	// add default fields
	fields = fields.concat([
	    {name: 'id', mapping: 'id'},
		{name: 'title',  mapping: 'title'}, 
		{name: 'authors',  mapping: 'authors'}, 
		{name: 'documentType',  mapping: 'documentType'},
		{name: 'year',  mapping: 'year'}, 
		{name: 'pages',  mapping: 'pages'},
		{name: 'publishedin',  mapping: 'publishedin'},
		{name: 'abstract',  mapping: 'abstract'},
		{name: 'keywords',  mapping: 'keywords'},
		{name: 'tags', mapping: 'tags'},
		{name: 'urls', mapping: 'urls'},
		{name: 'files', mapping: 'files'},
		{name: 'catalogs', mapping: 'catalogs'},
		{name: 'created_at', mapping: 'created_at'},
		{name: 'updated_at', mapping: 'updated_at'},
		{name: 'files',  mapping: 'files'}
	]);	
	
	switch( documentType ) {
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS:
			fields = fields.concat([
			    {name: 'tutors', mapping: 'thesis.tutors'},
			    {name: 'department', mapping: 'thesis.department'},
			    {name: 'faculty', mapping: 'thesis.faculty'},
			    {name: 'knowledgearea', mapping: 'thesis.knowledgeArea'}
			    ]);
			break;
		
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS:
			fields = fields.concat([
			    {name: 'tutors', mapping: 'masterThesis.tutors'},
			    {name: 'department', mapping: 'masterThesis.department'},
			    {name: 'faculty', mapping: 'masterThesis.faculty'},
			    {name: 'knowledgearea', mapping: 'masterThesis.knowledgeArea'}
			    ]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
			fields = fields.concat([
			    {name: 'tutors', mapping: 'phdThesis.tutors'},
			    {name: 'department', mapping: 'phdThesis.department'},
			    {name: 'faculty', mapping: 'phdThesis.faculty'},
			    {name: 'knowledgearea', mapping: 'phdThesis.knowledgeArea'}
			    ]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
			fields = fields.concat([
			    {name: 'city', mapping: 'magazineArticle.city'}
			    ]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
			fields = fields.concat([
			    {name: 'city', mapping: 'book.city'},
			    {name: 'edition', mapping: 'book.edition'},
			    {name: 'editors', mapping: 'book.editors'},
			    {name: 'publisher', mapping: 'book.publisher'},
			    {name: 'knowledgearea', mapping: 'book.knowledgeArea'}
			    ]);
			break;
			
		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
			fields = fields.concat([
			    {name: 'edition', mapping: 'encyclopedia.edition'},
			    {name: 'publisher', mapping: 'encyclopedia.publisher'},
			    {name: 'series_number', mapping: 'encyclopedia.series_number'}
			    ]);
			break;
	}
	
	return fields;
}

function previewRowRenderer(data) {
	if (data.documentType === undefined) {
		return;
	}
	
	var documentType = parseInt(data.documentType);
	var output = '<div class="test"><h3>' + data.title + '</h3></div>';
	
//		fields = fields.concat([
//		                	    {name: 'id', mapping: 'id'},
//		                		{name: 'title',  mapping: 'title'}, 
//		                		{name: 'authors',  mapping: 'authors'}, 
//		                		{name: 'documentType',  mapping: 'documentType'},
//		                		{name: 'year',  mapping: 'year'}, 
//		                		{name: 'pages',  mapping: 'pages'},
//		                		{name: 'publishedin',  mapping: 'publishedin'},
//		                		{name: 'abstract',  mapping: 'abstract'},
//		                		{name: 'keywords',  mapping: 'keywords'},
//		                		{name: 'tags', mapping: 'tags'},
//		                		{name: 'urls', mapping: 'urls'},
//		                		{name: 'files', mapping: 'files'},
//		                		{name: 'catalogs', mapping: 'catalogs'},
//		                		{name: 'created_at', mapping: 'created_at'},
//		                		{name: 'updated_at', mapping: 'updated_at'},
//		                		{name: 'files',  mapping: 'files'}
//		                	]);	
		                	
	switch( documentType ) {
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS:
//		filters = filters.concat([
//		    {type: 'string', dataIndex: 'tutors'},
//		    {type: 'string', dataIndex: 'department'},
//		    {type: 'string', dataIndex: 'faculty'},
//		    {type: 'string', dataIndex: 'knowledgearea'}
//		]);
		break;
	
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS:
//		filters = filters.concat([
//			    {type: 'string', dataIndex: 'tutors'},
//			    {type: 'string', dataIndex: 'department'},
//			    {type: 'string', dataIndex: 'faculty'},
//			    {type: 'string', dataIndex: 'knowledgearea'}
//			]);
		break;
		
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
//		filters = filters.concat([
//		    {type: 'string', dataIndex: 'tutors'},
//		    {type: 'string', dataIndex: 'department'},
//		    {type: 'string', dataIndex: 'faculty'},
//		    {type: 'string', dataIndex: 'knowledgearea'}
//		]);
		break;
		
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
//		filters = filters.concat([
//			    {type: 'string', dataIndex: 'city'}
//			]);
		break;
		
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
//		filters = filters.concat([
//		    {type: 'string', dataIndex: 'city'},
//		    {type: 'string', dataIndex: 'edition'},
//		    {type: 'string', dataIndex: 'editors'},
//		    {type: 'string', dataIndex: 'publisher'},
//		    {type: 'string', dataIndex: 'knowledgearea'}
//		]);
		break;
		
	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
//		filters = filters.concat([
//			    {type: 'string', dataIndex: 'edition'},
//			    {type: 'string', dataIndex: 'publisher'},
//			    {type: 'string', dataIndex: 'series_number'}
//			]);
		break;
	}
	
	return output;
}

function renderTitle(value, p, record){
    return String.format('<b>{0}</b>', value);
}

/**
 * Handler specified for the 'Available' column renderer
 * @param {Object} value
 */
function formatDateRenderer(value){
	if ((value !== undefined) && (typeof(value) == "string")) {
		//(value instanceof Date)
		var dt = Date.parseDate(value, "Y-m-d H:i:s");
		return dt.format('m/d/Y');
		//var dt = new Date();
		//console.log('value = ' + value);
		//dt = Date.parseDate(value, "Y-m-d H:i:s");
		//console.log('dt = ' + dt);
	  //return value.format('m/d/Y');
	}
	else {
		return '';
	}
}

/**
 * Handler specified for the 'Status' column renderer for the UserManager 
 * @param {Object} value
 */
function userStatusRenderer(value){
	if (value !== undefined ) {
		return value == 0 ? 'No' : 'Si';
	}
	else {
		return '';
	}
}